package com.wanmait.server.config;

import com.wanmait.server.Shiro.UserRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName ShiroConfig
 * @Author 羽
 * @Date 2020/12/10 22:34
 * @Version 1.0
 * shirod的通用化配置
 **/
@Configuration
public class ShiroConfig {
    /**
    * TODO
    * @author 羽
    * @date 2020/12/10 22:39
     * 安全管理器，管理subject
    **/
    @Bean
    public SecurityManager securityManager(UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        securityManager.setRememberMeManager(null);
        return securityManager;
    }

    /**
    * TODO
    * @author 羽
    * @date 2020/12/10 22:40
    *过滤链
    **/
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        //设定没登陆时，进入登陆界面
        shiroFilter.setLoginUrl("/login");


        //配置过滤链
        Map<String,String> filterMap = new LinkedHashMap<>();

//        filterMap.put("/swagger/**", "anon");
//        filterMap.put("/swagger-ui.html", "anon");
//        filterMap.put("/webjars/**", "anon");
//        filterMap.put("/swagger-resources/**", "anon");
        //访问静态资源时，可以匿名访问
        filterMap.put("/statics/**", "anon");
        filterMap.put("/verificationCode", "anon");

        //访问登陆界面，可以匿名访问
        filterMap.put("/login", "anon");
        filterMap.put("/demo", "anon");
        //访点击登录时，可以匿名访问
        filterMap.put("/loginVerification", "anon");
        filterMap.put("/favicon.ico", "anon");
        filterMap.put("/captcha.jpg", "anon");

        //除以上外都需要登陆
        filterMap.put("/**","authc");

        shiroFilter.setFilterChainDefinitionMap(filterMap);

        return shiroFilter;
    }

    /**
    * TODO
    * @author 羽
    * @date 2020/12/10 22:47
    * shiro的bean 的生命周期
    **/
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }


}
